﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Web;
using System.Collections;
using System.Threading;

namespace HttpRequestTools
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private string fileName = String.Empty;
        private string filePath = String.Empty;
        private delegate void ShowResponseText(string message);

        void SetMessage(string message)
        {
            txtResponse.Text = message;
        }

        void ShowMessage(string message)
        {
            if (this.InvokeRequired)
            {
                ShowResponseText d = new ShowResponseText(SetMessage);
                object[] arg = new object[] { message };//要传入的参数值      
                this.Invoke(d, arg);
                Thread.Sleep(1000);
            }
        }

        private string HttpPostFile(string postDataStr)
        {
            string URL = txtUrl.Text.Trim();
            if (postDataStr.Trim().Length > 0 && this.listView1.Items.Count > 0)
            {
                MessageBox.Show("请在Request Text和Body参数列表这2种传参方式中选择一种！");
                return "";
            }

            string result = string.Empty;
            if (listView1.Items.Count > 0)
            {
                Thread t = new Thread(new ParameterizedThreadStart(HttpPostList)); 
                t.Start(URL); 
            }

            if (postDataStr.Length > 0)
            {
                Thread t = new Thread(new ParameterizedThreadStart(HttpPostBodyStr)); 
                //result = HttpPostBodyStr(postDataStr);
                t.Start(postDataStr); 
            }

            return result;
        }


        private void HttpPostBodyStr(object _postDataStr)
        {
        
            string URL = txtUrl.Text.Trim();
            string postDataStr = _postDataStr.ToString();
            string retString = "";
            try
            {
                if (URL.IndexOf("http://") == -1) URL = "http://" + URL;
                linkLabel1.Text = URL;

                postDataStr = postDataStr.Trim();

                Encoding encoding = Encoding.UTF8;

                string result = string.Empty;
                string postBody = string.Empty;

                WebClient wc = new WebClient();
                //获取head参数
                foreach (ListViewItem item in this.listViewHeader.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    wc.Headers.Add(field, value);
                }

                if (txtHeader.Text.Trim().Length > 0)
                {
                    string[] paramAttr = txtHeader.Text.Split('&');
                    foreach (string param in paramAttr)
                    {
                        string[] keyValue = param.Split('=');
                        if (keyValue.Length > 0)
                        {
                            wc.Headers.Add(keyValue[0].Trim(), keyValue[1].Trim());
                        }
                    }
                }

                //获取body参数
                System.Collections.Specialized.NameValueCollection paramsVars = new System.Collections.Specialized.NameValueCollection();
                if (postDataStr.Trim().Length > 0)
                {
                    string[] paramAttr = postDataStr.Split('&');
                    foreach (string param in paramAttr)
                    {
                        string[] keyValue = param.Split('=');
                        if (keyValue.Length > 0)
                        {
                            paramsVars.Add(keyValue[0].Trim(), keyValue[1].Trim());
                        }
                    }
                }

                if (postDataStr.Trim().Length > 0 && paramsVars.Count == 0)
                {
                    byte[] postData = encoding.GetBytes(postDataStr);
                    byte[] responseData = wc.UploadData(URL, "POST", postData); // 得到返回字符流

                    retString = encoding.GetString(responseData);// 解码
                }

                if (paramsVars.Count > 0)
                {
                    byte[] byRemoteInfo = wc.UploadValues(txtUrl.Text.Trim(), "POST", paramsVars);
                    retString = System.Text.Encoding.Default.GetString(byRemoteInfo);
                }

                //return retString;
                ShowMessage(retString);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "同志，出错误啦！");
            }
        }

        private void HttpPostList(object _URL)
        {
            string URL = _URL.ToString();
            if (URL.IndexOf("http://") == -1) URL = "http://" + URL;
            linkLabel1.Text = URL;

            Hashtable headers = new Hashtable();
            ArrayList bytesArray = new ArrayList();
            // 生成需要上传的二进制数组
            CreateBytes cb = new CreateBytes();

            //获取head参数
            foreach (ListViewItem item in this.listViewHeader.Items)
            {
                string field = item.SubItems[0].Text;
                string value = item.SubItems[1].Text;
                //cb.Headers.Add(field, value);
                headers.Add(field, value);
            }

            if (txtHeader.Text.Trim().Length > 0)
            {
                string[] paramAttr = txtHeader.Text.Split('&');
                foreach (string param in paramAttr)
                {
                    string[] keyValue = param.Split('=');
                    if (keyValue.Length > 0)
                    {
                        headers.Add(keyValue[0].Trim(), keyValue[1].Trim());
                    }
                }
            }

            foreach (ListViewItem item in this.listView1.Items)
            {
                string field = item.SubItems[0].Text;
                string value = item.SubItems[1].Text;
                //PostVars.Add(field, value);

                if (field == fileName && value == filePath)
                {
                    FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    byte[] fileBytes = new byte[fs.Length];
                    bytesArray.Add(cb.CreateFieldData(field, filePath, "application/octet-stream", fileBytes));
                }
                else
                {
                    bytesArray.Add(cb.CreateFieldData(field, value));
                }
            }

            // 合成所有表单并生成二进制数组
            byte[] bytes = cb.JoinBytes(bytesArray);

            // 返回的内容
            byte[] responseBytes;
            Encoding encoding = Encoding.UTF8;

            // 上传到指定Url
            bool uploaded = cb.UploadData(URL, headers, bytes, out responseBytes);
            string retString = encoding.GetString(responseBytes);// 解码

            //return retString;
            ShowMessage(retString);
        }



        private string HttpPost(string URL, string postDataStr)
        {
            string retString = "";
            try
            {
                if (URL.IndexOf("http://") == -1) URL = "http://" + URL;
                linkLabel1.Text = URL;

                postDataStr = postDataStr.Trim();

                Encoding encoding = Encoding.UTF8;

                string result = string.Empty;
                string postBody = string.Empty;

                WebClient wc = new WebClient();

                //获取head参数
                foreach (ListViewItem item in this.listViewHeader.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    wc.Headers.Add(field, value);
                }

                //获取body参数
                //System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
                foreach (ListViewItem item in this.listView1.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    //PostVars.Add(field, value);

                    if (field == fileName && value == filePath)
                    {
                        FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                        byte[] byteFile = new byte[fs.Length];
                        fs.Read(byteFile, 0, Convert.ToInt32(fs.Length));
                        fs.Close();

                        wc.Headers.Add("Content-Type", "multipart/form-data");
                        value = HttpUtility.UrlEncode(Convert.ToBase64String(byteFile));
                    }

                    if (postBody.Length == 0)
                    {
                        postBody = field + "=" + value;
                    }
                    else
                    {
                        postBody = postBody + "&" + field + "=" + value;
                    }
                }

                if (postDataStr.Trim().Length > 0 && this.listView1.Items.Count > 0)
                {
                    MessageBox.Show("请在Request Text和Body参数列表这2种传参方式中选择一种！");
                    return "";
                }

                string POST_DATA = string.Empty;
                if (postDataStr.Length > 0 && postBody.Length > 0)
                {
                    POST_DATA = postDataStr + "&" + postBody;
                }
                else
                {
                    POST_DATA = postDataStr + postBody;
                }

                if (POST_DATA.Trim().Length > 0)
                {
                    byte[] postData = encoding.GetBytes(POST_DATA);
                    byte[] responseData = wc.UploadData(URL, "POST", postData); // 得到返回字符流

                    retString = encoding.GetString(responseData);// 解码


                }

                return retString;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "同志，出错误啦！");
            }

            return retString;
        }

        private string HttpPost1(string URL, string postDataStr)
        {
            string retString = "";
            try
            {
                if (URL.IndexOf("http://") == -1) URL = "http://" + URL;
                linkLabel1.Text = URL;

                postDataStr = postDataStr.Trim();

                Encoding encoding = Encoding.UTF8;

                string result = string.Empty;
                string postBody = string.Empty;

                WebClient wc = new WebClient();
                //获取head参数
                foreach (ListViewItem item in this.listViewHeader.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    wc.Headers.Add(field, value);
                }

                //获取body参数
                System.Collections.Specialized.NameValueCollection PostVars = new System.Collections.Specialized.NameValueCollection();
                foreach (ListViewItem item in this.listView1.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    PostVars.Add(field, value);
                }

                if (postDataStr.Trim().Length > 0 && this.listView1.Items.Count > 0) {
                    MessageBox.Show("请在Request Text和Body参数列表这2种传参方式中选择一种！");
                    return "";
                }

                System.Collections.Specialized.NameValueCollection paramsVars = new System.Collections.Specialized.NameValueCollection();
                if (postDataStr.Trim().Length > 0)
                {
                    string[] paramAttr = postDataStr.Split('&');
                    foreach (string param in paramAttr)
                    {
                        string[] keyValue = param.Split('=');
                        if (keyValue.Length > 0)
                        {
                            paramsVars.Add(keyValue[0].Trim(), keyValue[1].Trim());
                        }
                    }

                    if (paramsVars.Count == paramAttr.Length)
                    {
                        PostVars.Add(paramsVars);
                    }
                }

                if (postDataStr.Trim().Length > 0 && paramsVars.Count == 0)
                {
                    byte[] postData = encoding.GetBytes(postDataStr);
                    byte[] responseData = wc.UploadData(URL, "POST", postData); // 得到返回字符流

                    retString = encoding.GetString(responseData);// 解码
                }

                if (PostVars.Count > 0)
                {
                    byte[] byRemoteInfo = wc.UploadValues(URL, "POST", PostVars);
                    retString = System.Text.Encoding.Default.GetString(byRemoteInfo);
                }

                return retString;
            }
            catch (Exception e) {
                MessageBox.Show(e.Message, "同志，出错误啦！");
            }

            return retString;
        }

        public string HttpGet(string URL, string postDataStr)
        {
            string retString = "";
            try
            {
                WebClient myClient = new WebClient();
                myClient.Encoding = Encoding.UTF8;
                StringBuilder sbParams = new StringBuilder();
                foreach (ListViewItem item in this.listView1.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    if (sbParams.Length > 0)
                    {
                        sbParams.Append("&&");
                    }

                    sbParams.Append(field).Append("=").Append(value);
                }

                if (sbParams.Length > 0)
                {
                    URL = URL + "?" + sbParams.ToString();
                }
                if (postDataStr.Trim().Length > 0)
                {
                    if (postDataStr.IndexOf("?") != -1)
                    {
                        URL = URL + "&" + postDataStr;
                    }
                    else
                    {
                        URL = URL + "?" + postDataStr;
                    }
                }

                //获取head参数
                foreach (ListViewItem item in this.listViewHeader.Items)
                {
                    string field = item.SubItems[0].Text;
                    string value = item.SubItems[1].Text;
                    myClient.Headers.Add(field, value);
                }

                if (txtHeader.Text.Trim().Length > 0)
                {
                    string[] paramAttr = txtHeader.Text.Split('&');
                    foreach (string param in paramAttr)
                    {
                        string[] keyValue = param.Split('=');
                        if (keyValue.Length > 0)
                        {
                            myClient.Headers.Add(keyValue[0].Trim(), keyValue[1].Trim());
                        }
                    }
                }

                if (URL.IndexOf("http://") == -1 && URL.IndexOf("https://") == -1) URL = "http://" + URL;
                linkLabel1.Text = URL.Replace("&","&&");

                string result = myClient.DownloadString(URL);
                return result;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message, "同志，出错误啦！");
            }

            return retString;

        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            String responseText = String.Empty;
            try
            {
                responseText = HttpGet(txtUrl.Text.Trim(), txtRequest.Text);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            txtResponse.Text = responseText;
        }

        private void btnPost_Click(object sender, EventArgs e)
        {
            String responseText = String.Empty;
            try
            {
                responseText = HttpPostFile(txtRequest.Text.Trim());
            } catch(Exception ex) {
                MessageBox.Show(ex.Message);
            }

            txtResponse.Text = responseText;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.TopMost = false;
            this.txtUrl.Text = "www.baidu.com";
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string field = txtName.Text;
            string value = txtValue.Text;
            if (value == filePath) fileName = field;
            this.listView1.Items.Add(new ListViewItem(new string[] { field, value }));
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            this.listView1.Items.Clear();
        }

        private void btnAddHeader_Click(object sender, EventArgs e)
        {
            string field = txtHeadField.Text;
            string value = txtHeadValue.Text;
            this.listViewHeader.Items.Add(new ListViewItem(new string[] { field, value }));
        }

        private void btnClearText_Click(object sender, EventArgs e)
        {
            txtResponse.Text = "";
        }

        private void btnClearHeader_Click(object sender, EventArgs e)
        {
            listViewHeader.Items.Clear();
        }

        private void txtUrl_Leave(object sender, EventArgs e)
        {
            if (txtUrl.Text.IndexOf("http://") == -1 && txtUrl.Text.IndexOf("https://") == -1) txtUrl.Text = "http://" + txtUrl.Text;
        }

        StreamWriter writer;
        StreamReader reader;
        FileStream fs;

        private void btnSelect_Click(object sender, EventArgs e)
        {
            openFileDialog1.InitialDirectory = Application.ExecutablePath;
            //openFileDialog1.Filter = "All Files(*.*)|*.*";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                filePath = openFileDialog1.FileName;
                try
                {
                    fs = new FileStream(filePath, FileMode.Open);
                    reader = new StreamReader(fs);
                    txtValue.Text = filePath;
                }
                catch (Exception excep)
                {
                    MessageBox.Show(excep.Message);
                }
                finally
                {
                    reader.Close();
                    fs.Close();
                }
            }
        }

        private void saveFile() 
        {
            try
            {
                fs = new FileStream(filePath, FileMode.Create);
                writer = new StreamWriter(fs);
                writer.Write(filePath);
            }
            catch (Exception excep)
            {
                MessageBox.Show(excep.Message);
            }
            finally
            {
                writer.Flush();
                writer.Close();
                fs.Close();
            }
        }
    }
}
